from rest_framework import serializers
from study.models import Student, Classes


# class StudentSerializer(serializers.Serializer):  # 格式（abcs.ABC）
#     # 返回字段数据和字段的校验
#     id = serializers.IntegerField(label='ID', read_only=True)  # 只允许读
#     name = serializers.CharField(max_length=20, label='姓名')
#     age = serializers.IntegerField(label='年龄', required=False)  # 此字段非必填
#     sex = serializers.IntegerField(label='性别')
#     c_time = serializers.DateTimeField(label='创建时间')
#     u_time = serializers.DateTimeField(label='修改时间')
#     is_delete = serializers.BooleanField(label='逻辑删除')
class StudentSerializer(serializers.ModelSerializer):
    # classes = serializers.StringRelatedField(read_only=True)  # 前端显示关联字段的verbose_name，但一般不会这样写，这样会把原字段覆盖掉
    class_name = serializers.CharField(read_only=True, source='classes.name')  # 另外自定义字段
    class_num = serializers.CharField(read_only=True, source='classes.num')  # 另外自定义字段

    class Meta:
        model = Student
        fields = '__all__'

        # 校验：age有效范围0-200，extra_kwargs:给指定属性添加或者修改参数
        extra_kwargs = {
            'age': {
                'min_value': 0,
                'max_value': 200
            }
        }

    # 自定义校验方法，对指定属性进行校验

    # def validate_name(self, attrs):
    #     if 'python' not in attrs.lower():
    #         raise serializers.ValidationError('name error')
    #     return attrs
    # def validate(self, attrs):
    #     if 'python' not in attrs['name'].lower():
    #         raise serializers.ValidationError('name error')
    #     return attrs


class SimpleStudentSerializer(serializers.ModelSerializer):  # 简化需要的学生信息
    class Meta:
        model = Student
        fields = ['id', 'name']


class ClassesSerializer(serializers.ModelSerializer):
    # student_set = StudentSerializer(read_only=True, many=True)  # 另外自定义字段
    student_set = SimpleStudentSerializer(read_only=True, many=True)  # 用简化版的字段

    class Meta:
        model = Classes
        fields = '__all__'

    def validate_name(self, attrs):
        if 'python' not in attrs.lower():
            raise serializers.ValidationError('班级名必须有python')
        return attrs
